package com.hxzy.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.bean.User;
import com.hxzy.bean.UserState;
import com.hxzy.service.UserService;
import com.hxzy.service.impl.UserServiceImpl;
import com.hxzy.util.CommonUtil;
import com.hxzy.vo.JsonResult;
import com.hxzy.vo.StatusCode;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.filefilter.SuffixFileFilter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;

/**
 * @author nick
 */
@WebServlet("/doRegister")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        //System.out.println("是否支持commons file upload转换request请求" + ServletFileUpload.isMultipartContent(req));

        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Configure a repository (to ensure a secure temp location is used)
        //ServletContext servletContext = this.getServletConfig().getServletContext();
        java.io.File repository = new File("D:\\tempDir"); //指定临时目录
        factory.setRepository(repository);

        // 用例处理request请求
        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setFileSizeMax(1024*1024); //设置允许上传的文件大小上限阈值    1M，  1KB = 1024byte   1MB=1024KB

        //实例化一个空的对象
        final User user = new User();
        //即使出现异常，也要告诉用户
        JsonResult jsonResult = new JsonResult();

        String[]  limit = new String[]{".jpg", ".gif", ".png", ".bmp"};
        //定义限制的文件类型
        SuffixFileFilter filter = new SuffixFileFilter(limit);
        try {
            // 转换request请求
            List<FileItem> items = upload.parseRequest(req);
            items.stream().forEach(t -> {
                if (t.isFormField()) { //是一个表单元素
                    String fieldName = t.getFieldName();//account,nickName,password,gender
                    try {
                        //对url参数进行解码
                        String userDecode = URLDecoder.decode(t.getString(),"utf-8");
                        //URLDecoder.decode("","UTF-8");
                        //通过Commons bean util为对象user中的属性赋值
                        BeanUtils.setProperty(user, fieldName, userDecode);

                        if (fieldName.equals("gender")) {
                            if (t.getString().equals("1")) { //性别为男
                                user.setPic("boy.png");
                            } else { //性别为女
                                user.setPic("girl.png");
                            }
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else { //是一个上传的文件
                    String fileName = t.getName();//上传的文件名
                    String fieldName = t.getFieldName();  //提交表单时设置的name属性，pic
                    String contentType = t.getContentType(); //文件的MIME类型；  Image/jpeg
                    boolean isInMemory = t.isInMemory();    //如果文件过大，会保存在临时目录，否则保存在内存
                    long sizeInBytes = t.getSize(); //获取文件的大小，返回字节数

                    long l = CommonUtil.localDateTime2mills(LocalDateTime.now());//得到当前时间的毫秒数

                    int index = fileName.lastIndexOf(".");
                    String subfix = fileName.substring(index);
                    String newFileName = l + subfix;//login.jpg 转换为  123456.jpg
                    String path = "D:\\upload\\" + newFileName;
                    File file = new File(path);
                    boolean accept = filter.accept(file);
                    if (accept) {
                        //将文件保存到本地磁盘
                        try {
                            t.write(file);
                            user.setPic(newFileName);//设置头像的文件名
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        jsonResult.setCode(400);
                        jsonResult.setMessage("只能上传图片文件");
                        try {
                            JsonResult.write2client(jsonResult, resp);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return;
                    }
                }
            });

            //调用业务逻辑层完成注册用户
            UserService service = new UserServiceImpl();

            User byAccount = service.findByAccount(user.getAccount());
            System.out.println(user);

            if (byAccount != null) { //再一次根据用户名查询的逻辑，一旦用户不为null，说明存在同名账户
                jsonResult.setCode(StatusCode.LOCKED.getCode());
                jsonResult.setMessage("该用户已经注册");
                JsonResult.write2client(jsonResult, resp);
                return;
            }

            int save = service.save(user);
            if (save > 0) {
                jsonResult.setCode(StatusCode.SUCCESS.getCode());
                jsonResult.setMessage(StatusCode.SUCCESS.getMessage());
            } else {
                jsonResult.setCode(StatusCode.UNKNOWN_ERROR.getCode());
                jsonResult.setMessage(StatusCode.UNKNOWN_ERROR.getMessage());
            }

        } catch (FileUploadException e) {
            jsonResult.setCode(StatusCode.EXCEPTION.getCode());
            jsonResult.setMessage("上传文件失败");
        } catch (Exception e) {
            jsonResult.setCode(StatusCode.UNKNOWN_ERROR.getCode());
            jsonResult.setMessage(StatusCode.UNKNOWN_ERROR.getMessage());
        }

        System.out.println(JSONObject.toJSONString(jsonResult));
        JsonResult.write2client(jsonResult,resp);

    }
}
